package com.TT.controller;

import com.TT.pojo.Books;
import com.TT.service.BooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/books")
public class BooksController {

    @Autowired
    private BooksService booksService;

    /**
     * 查询全部的书籍，并且返回到一个书籍展示页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/allBook")
    public String list(Model model) {

        List<Books> books = booksService.queryAllBooks();

        model.addAttribute("list", books);

        return "allBook";


    }

    @RequestMapping("/toAddPage")
    public String toAddPage() {
        return "addBook";
    }


    @RequestMapping("/addBooks")
    public String addBooks(Books books) {
        booksService.addBooks(books);
        return "redirect:/books/allBook";  //重定向到allBook请求
    }

    @RequestMapping("/toUpdatePage")
    public String toUpdatePage(int bookID,Model model) {
        Books books = booksService.queryBooksById(bookID);
        model.addAttribute("books",books);
        return "updateBook";
    }


    @RequestMapping("/updateBooks")
    public String updateBooks(Books books) {
        booksService.updateBooks(books);
        return "redirect:/books/allBook";
    }

    @RequestMapping("/deleteBooks/{bookID}")
    public String deleteBooks(@PathVariable("bookID") int bookID) {
        booksService.deleteBooksById(bookID);
        return "redirect:/books/allBook";
    }

    @RequestMapping("/queryBooks")
    public String queryBooks(String queryBookName,Model model){

        Books books = booksService.queryBooksByName(queryBookName);
        List<Books> list = new ArrayList<Books>();
        list.add(books);


        if(books == null) {
            list = booksService.queryAllBooks();
            model.addAttribute("error","未查到");
        }
        model.addAttribute("list", list);

        return "allBook";
    }


}
